package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityBiddingCargoPublishContactBinding;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.adapter.transport.BiddingCargoPublishContactAdapter;
import com.sgb.kjwl.viewmodel.transport.CargoPublishPublisherViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2020/12/29 17:50
 * @Description: 竞价货源发布联系信息页面
 */
public class BiddingCargoPublishContactActivity extends AppActivity {

    CargoPublishPublisherViewModel viewModel;
    ActivityBiddingCargoPublishContactBinding binding;
    //联系人列表
    private List<CargoPublishEntity.ContactInfoEntity> mList;
    private BiddingCargoPublishContactAdapter mAdapter;
    private View mAddFooter;
    //数据实体类
    private CargoPublishEntity mEntity;

    public static void start(Activity activity, CargoPublishEntity entity, int requestCode) {
        Intent intent = new Intent(activity, BiddingCargoPublishContactActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(RouterKey.DATA, entity);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(CargoPublishPublisherViewModel.class);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_bidding_cargo_publish_contact);
        binding.setLifecycleOwner(this);
        binding.includeTitle.titleView.setText("联系信息");
        initRecycler();
        initEvent();
        initData();
    }

    private void initRecycler() {
        mList = new ArrayList<>();
        mAdapter = new BiddingCargoPublishContactAdapter(mList);
        binding.rvReleaseCargoContact.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .color(Color.TRANSPARENT)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(binding.rvReleaseCargoContact);
        binding.rvReleaseCargoContact.setAdapter(mAdapter);
       // initFooter();
    }

    private void initFooter() {
        //设置尾部添加按钮
        mAddFooter = View.inflate(this, R.layout.footer_bidding_cargo_add_contact, null);
        mAddFooter.setOnClickListener(v -> {
            mList.add(new CargoPublishEntity.ContactInfoEntity());
            mAdapter.notifyDataSetChanged();
            checkAddEnabled();
        });
        mAdapter.addFooterView(mAddFooter);
    }

    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
        //删除联系人
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mList.remove(position);
                mAdapter.notifyDataSetChanged();
                checkAddEnabled();
            }
        });
    }

    private void initData() {
        mEntity = getIntent().getParcelableExtra(RouterKey.DATA);
        if (mEntity == null) {
            mEntity = new CargoPublishEntity();
        }
        //默认设置登录人信息
        if (mEntity.getContactInfo() == null) {
            List<CargoPublishEntity.ContactInfoEntity> contactInfo = new ArrayList<>();
            CargoPublishEntity.ContactInfoEntity contact = new CargoPublishEntity.ContactInfoEntity();
            contact.setContrcts(UserOperating.getInstance().getUserRealName());
            contact.setContrctsNumber(UserOperating.getInstance().getPhone());
            contactInfo.add(contact);
            mEntity.setContactInfo(contactInfo);
        }
        syncData();
    }

    private void syncData() {
        //联系人信息
        if (ArrayUtil.isNotNullAndEmpty(mEntity.getContactInfo())) {
            mList.addAll(mEntity.getContactInfo());
            //设置第一个类型为无删除类型
            mList.get(0).setItemType(SingleItemConstant.TYPE_ONE);
            mAdapter.notifyDataSetChanged();
        }
       // checkAddEnabled();
    }

    /**
     * 判断是否可点击添加联系人
     */
    private void checkAddEnabled() {
        //判断是否可点击
        if (mList.size() >= 3) {
            mAddFooter.setEnabled(false);
            mAddFooter.setAlpha(0.5f);
        } else {
            mAddFooter.setEnabled(true);
            mAddFooter.setAlpha(1f);
        }
    }

    @Override
    public void onClick(View v) {
        if (v == binding.includeTitle.ivBack) {
            finish();
        } else if (v == binding.tvReleaseCargoSubmit) {
            clearAllFocus();
            checkData();
        }
    }

    /**
     * 检查数据并回传
     */
    private void checkData() {
        if (mEntity == null) return;
        //todo 检查联系人信息，提示信息调整
        for (int i = 0; i < mList.size(); i++) {
            CargoPublishEntity.ContactInfoEntity contact = mList.get(i);
            if (TextUtils.isEmpty(contact.getContrcts()) || TextUtils.isEmpty(contact.getContrctsNumber())) {
                MToast.showToast(this, i == 0
                        ? "请填写联系人信息"
                        : String.format("请填写%s号联系人信息", i));
                return;
            }
        }
        //设置联系人信息
        mEntity.setContactInfo(mList);
        Intent intent = new Intent();
        intent.putExtra(RouterKey.DATA, mEntity);
        setResult(RESULT_OK, intent);
        finish();
    }
}
